package com.ruoyi.web.controller.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController  //如果使用 RestController  则方法上不需要再标志 ResponseBody http://localhost:8080/oa-erp/users/info/update?id=1&name=test
@RequestMapping("/HandleMsg")
public class HandleMsg {
    private static Logger logger = LoggerFactory.getLogger(HandleMsg.class);
    @Autowired
    private JdbcSql jbcOracle;
    private static String UserId = Common.SessionGet("UserName");
    PageModel page = new PageModel();  //下面分页
    //获取右下角通知
    @CrossOrigin
    @PostMapping("/getNewsInfo")
    public void getNewsInfo()
    {
        String CatName = Common.Utf8Rquest("cat_name"), cat_id = Common.Utf8Rquest("cat_id"), id = Common.Utf8Rquest("id"), UserId1 = Common.Utf8Rquest("UserId");
        if (id.equals("null") || id.equals("undefined")) { Common.ResponseWrite(""); return; }
        if (cat_id.equals("8888")) JdbcSql.ExecuteSQL("update xoalanemail set readtime=now() where id='" + id + "'");//阅读量加1
        else JdbcSql.Exec1SqlBatch("update WAWebNews set clickcnt=ifnull(clickcnt,0)+1 where id='" + id + "'");//阅读量加1/积分加1  http://171.106.48.50:3000/UploadFile/UEditor/2016-10-14/7510eb5f-0262-4fd0-9c20-0b4a112c0a97.png
        String sql = "select a.id,a.title,a.keyword,a.icon,a.pid,content content,a.newstype,a.iftop,a.ifimportant,a.brief,a.author,a.srcurl,clickcnt," +
                "sharecnt,getdate(timestr,'s') timestr,a.viewdept,a.limits,a.displaymode,a.AuditStatus,GetCodeNameByID('AuditState',a.AuditStatus) StateEx,a.UserID," +
                "a.OperTime,getUserNameByID(UserID) User1,REPLACE(a.fujian,'||','|') fujian," +
                "case when newstype in (2,3) then (select concat(id,'`',title) from WAWebNews where pid=a.pid and id<a.id order by id desc limit 1) else '' end preurl," +
                "case when newstype in (2,3) then (select concat(id,'`',title) from WAWebNews where pid=a.pid and id>a.id order by id  limit 1) else '' end nexturl," +
                "ZanCnt from WAWebNews a where id='" + id + "'";
        if (cat_id.equals("8888")) sql = "select id,EmailTitle title,concat(EmailTitle,'<br/>',ifnull(emailcontent,'')) content,getdate(TimeStr,'d') OperTime,'^xcnt^' Xcnt from XOALanEmail a where id='0" + id + "' ";
        Common.ResponseWrite(Common.DataTable2Json(JdbcSql.GetDataSet(sql)));
    }
    //获取新闻标题
    @CrossOrigin
    @PostMapping("/getNewsList")
    public void getNewsList()
    {UserId="1";
        String pid=Common.Utf8Rquest("cat_id"),UserId= Common.SessionGet("UserName"), searchkey=Common.Utf8Rquest("q"), top = "", cnt0 = "0", readflag = Common.Utf8Rquest("readflag"),catname=Common.Utf8Rquest("cat_name"),NoReadSms=" and  EmailState in ('未读','未签收') ";
        //if(UserId.equals("")){Common.ResponseWrite("会话不存在");return;}
        if (readflag.equals("0")) readflag = "  " + NoReadSms;
        else if (readflag.equals("1")) readflag = " and readtime>'2000-01-01' and  EmailState in ('已读','已签收')  ";
        else readflag = "";
        String sql = "select  a.id id,a.pid,a.title name,content desc1,getdate(timestr,'d') p5,'^xcnt^' Xcnt from wawebnews a,waindextab b where a.pid=b.id and b.name='" + catname + "' ";
        if (pid.equals( "8888")) sql = "select id,EmailTitle name,ifnull(substring(emailcontent,1,10),'') desc1,getdate(TimeStr,'d') p5,'^xcnt^' Xcnt from XOALanEmail a where touser='" + UserId + "' " +  readflag;//CatName.Contains("系统推送消息")
        else if (pid.equals( "9887")) sql = "select a.id id,a.pid,a.title name,'' desc1,getdate(timestr,'d') p5,'^xcnt^' Xcnt,'' srcurl from wawebnews a where title like '%" + searchkey + "%' " ;//CatName.Contains("系统推送消息")

        else if (!Common.isStrEmpty(pid)) sql = "select a.id id,a.pid,a.title name,content desc1,getdate(timestr,'d') p5,'^xcnt^' Xcnt from wawebnews a where pid=" + pid;//按照cat_id获取列表
        System.out.println(pid+"==="+sql);
        MySqlPaging( sql);
    }
    private void MySqlPaging(  String sql)
    {
        int count = 0;String pageCur=Common.Utf8Rquest("page");
        if (Common.isStrEmpty(pageCur)) { Common.ResponseWrite(Common.DataTable2Json(JdbcSql.GetDataSet(sql))); return; }
        page.Field = Common.GetStrBetween(sql, "select ", "from ");
        page.Order = "order by a.id desc";
        page.Page = Integer.parseInt(pageCur);
        page.Table = Common.GetStrBetween(sql, "from ", "where ");
        page.Top = 20;
        page.Where = " and " + sql.substring(sql.indexOf("where ") + 6);
        String PageSql = "select " + page.Field + " from " + page.Table + " where 1=1 " + page.Where + " " + page.Order;
        //Common.ResponseWrite(PageSql); return;
        List<Map<String, Object>> ds = Common.DbPageFunc(page);
        Common.ResponseWrite ("{\"pagecnt\":" + Math.ceil(page.RecCnt * 1.0 / page.Top) + ",\"reccnt\":" +page.RecCnt+ ",\"perpagecnt\":"+ page.Top+ ",\"pagelimit\":\""+ ""  + "\",\"rows\":" + Common.DataTable2Json(ds) + "}");
        //Common.ResponseWrite(Common.DataTable2Json(Common.DbPageFunc(page )));
    }
    //获取左下角提醒个数
    @CrossOrigin
    @PostMapping("/ReadUserMsg")
    public void ReadUserMsg() {//加入唯一终端登录:1.登录的时候写入SessionId  2.此处获取SessionId=自己并且登录时间在5分钟内,否则就退出
        //检查session是否过期
        String UserId = Common.SessionGet("UserName");
        if (UserId.equals("")) { Common.ResponseWrite("{error:true}"); return; }
        if (!Common.Utf8Rquest("readed_id").equals("") )
            JdbcSql.ExecuteSQL("update XOALanEmail set EmailState='已读',readtime=now() where id='" + Common.Utf8Rquest("readed_id") + "'");
    }
    @CrossOrigin
    @PostMapping("/getMoneyRate")
    public void getMoneyRate() {//获取汇率
        List<Map<String, Object>> dt1=JdbcSql.GetDataSet("select code,name,round(abs(name-f1)/name*100,2) per,DATEDIFF(opertime,now()) df from rzcode where type='汇率'");
        if(!(dt1.get(0).get("df").toString().equals("0"))) {//从网站获取数据
            String RateStr=//"{\"reason\":\"查询成功!\",\"result\":{\"update\":\"2022-05-24 18:51:24\",\"list\":[[\"美元\",\"100\",\"665.81\",\"660.39\",\"668.63\",\"668.63\"],[\"瑞典克朗\",\"100\",\"67.78\",\"65.69\",\"68.65\",\"68.32\"],[\"卢布\",\"100\",\"11.27\",\"10.75\",\"12.25\",\"11.73\"],[\"新西兰元\",\"100\",\"427.75\",\"414.55\",\"436.68\",\"430.75\"],[\"韩元\",\"100\",\"0.5255\",\"0.507\",\"0.5491\",\"0.5297\"],[\"日元\",\"100\",\"5.2155\",\"5.0535\",\"5.262\",\"5.2539\"],[\"港币\",\"100\",\"84.81\",\"84.14\",\"85.15\",\"85.15\"],[\"英镑\",\"100\",\"832.42\",\"806.56\",\"842.26\",\"838.55\"],[\"欧元\",\"100\",\"712.21\",\"690.08\",\"719.77\",\"717.46\"],[\"瑞士法郎\",\"100\",\"688.4\",\"667.16\",\"696.21\",\"693.24\"],[\"加拿大元\",\"100\",\"519.88\",\"503.46\",\"526.02\",\"523.71\"],[\"澳大利亚元\",\"100\",\"470.66\",\"456.04\",\"476.22\",\"474.12\"]]},\"error_code\":0}";
                    Common.getHttpRequestData("http://op.juhe.cn/onebox/exchange/query?key=0fa25f736209d55d8badedd2525baa34","");
            RateStr=RateStr.replace("\"","");
            String USD=Common.GetStrBetween(RateStr,"美元,100,",","),EUR=Common.GetStrBetween(RateStr,"欧元,100,",","),HKD=Common.GetStrBetween(RateStr,"港币,100,",",");
            JdbcSql.Exec1SqlBatch("update rzcode set name="+USD+",opertime=now() where type='汇率' and code='USD';update rzcode set name="+EUR
                    +",opertime=now() where type='汇率' and code='EUR';update rzcode set name="+HKD+",opertime=now() where type='汇率' and code='HKD';");
            dt1=JdbcSql.GetDataSet("select code,name,round(abs(name-f1)/name*100,2) per,DATEDIFF(opertime,now()) df from rzcode where type='汇率'");
        }
        Common.ResponseWrite (Common.DataTable2Json(dt1) );
    }
        //获取左下角提醒个数
        @CrossOrigin
        @PostMapping("/showOnlineMsgCnt")
        public void showOnlineMsgCnt() {//加入唯一终端登录:1.登录的时候写入SessionId  2.此处获取SessionId=自己并且登录时间在5分钟内,否则就退出
            //检查session是否过期
            String UserId=Common.SessionGet("UserName");String jiaose = Common.SessionGet("JiaoSe").toString();String strRId = Common.Utf8Rquest("readed_id");
            if (UserId.equals("")) { Common.ResponseWrite("{error:true}"); return; }
            if(strRId.equals("-1")){Common.ResponseWrite(JdbcSql.GetSHSL("select count(1) FROM XOALanEmail a WHERE touser="+UserId+" and EmailState in ('未读')"));return;}
            JdbcSql.ExecuteSQL("update XOAUser set ActiveTime=now() where state=1 and  UserName='" + UserId + "'");//刷新当前用户的激活时间
            if (!Common.Utf8Rquest("readed_id").equals("") && Common.Utf8Rquest("mode").equals("2"))
                JdbcSql.ExecuteSQL("update XOALanEmail set EmailState='已读' where EmailState in ('未读') and id='" + Common.Utf8Rquest("readed_id") + "'");
            else if (Common.Utf8Rquest("mode").equals("100")) {
                JdbcSql.ExecuteSQL("update XOALanEmail set EmailState='已读' where EmailState in ('未读') and touser='" + UserId + "'");
                return;
            }

            if (strRId.equals("")) strRId = "0";
            String SQL = "SELECT 0 onlinecnt ,60 jiange ,1 mailcnt, '是' iftixing ,'' hMailID,'' editTitle,'' lMailType,'' lSrcId,'' lblSender,'' lblTime,'' iPayAnother,'' ViewUrl UNION ALL\n" +
                    "select 0 onlinecnt ,60 jiange ,0 mailcnt ,'是' iftixing ,a.ID,EmailTitle EmailTitle,c.TabNameChn EmailType,srcid,GetUserNameOnlyByID(fromuser)fromuser  ,getdate(TimeStr,'s') as TimeStr,39999 iPayAnother,通知反馈链接 ViewUrl "
			    + " FROM XOALanEmail a  ,TwReportTable c WHERE touser="+UserId+" and EmailState in ('未读','未签收')   and c.syscode=EmailType ORDER BY 1 desc  limit 10;";
            List<Map<String, Object>> t = JdbcSql.GetDataSet(SQL);
            Common.ResponseWrite(Common.DataTable2Json(t));
        }

    @CrossOrigin
    @PostMapping("/TestFunc")
    public void TestFunc()   {//发短信
        logger.info(Common.browserName());
    }
    }

